<template>
  <div>
    <p>Home Page: {{ count }}</p>
    <nuxt-img src="/images/1.jpg" width="300" height="400" alt="1" />
    <nuxt-link to="/login">登录</nuxt-link>
    <el-button :loading="loading" type="primary" @click="login">登录</el-button>
    <el-button v-for="locale in locales" :key="locale.code" type="primary" @click="setLocale(locale.code)">
      {{ locale.name }}
    </el-button>
    <h1>{{ $t("welcome") }}</h1>
  </div>
</template>

<script lang="ts" setup>
import useCountStore from "~/stores/count"
import useHomeStore from "~/stores/home"
import { userLogin } from "~/api/modules/home"

const { locales, setLocale } = useI18n()

const countStore = useCountStore()
const { count } = storeToRefs(countStore)
const homeStore = useHomeStore()

const loading = ref(false)

const login = async () => {
  loading.value = true

  try {
    const res = await userLogin({
      username: "admin",
      password: "123456"
    })

    if (res.data) {
      const token = useCookie("token")
      token.value = res.data.token
      homeStore.setUsernameAction(res.data.username)
      navigateTo("/")
    }
  } catch (e) {
    console.error("登录失败:", e)
  } finally {
    loading.value = false
  }
}

useHead({
  title: "首页"
})
</script>

<style lang="scss" scoped></style>
